﻿using OnlineCourse.Model.Entity;
using OnlineCourse.Services.IServices;
using System;
using System.Collections.Generic;
using System.Text;
using OnlineCourse.Model;
using System.Linq;
using OnlineCourse.Services.Model;
namespace OnlineCourse.Services
{
    public class BuyOrderService : IBuyOrdeServicer

    {
        public readonly ApplicationDbContext _db;
        public BuyOrderService(ApplicationDbContext db)
        {
            this._db = db;
        }

        /// <summary>
        /// 购买一门课程不用券
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="courseid"></param>
        /// <returns></returns>
        public bool BuyOrderAdd( out int mes,Guid userid, Guid courseid)
        {
            bool mark = false;
            //先判断会员余额够不够买
            BuyOrder bo = new BuyOrder();
            var isbo = _db.BuyOrders.Where(a => a.CourseId == courseid && a.UserId == userid).FirstOrDefault();
            if (isbo != null)
            {
                mes = 1;//已经购买过该课程不能再次购买！
                return false;
            }
            User u = new User();
            Course c = new Course();
            u = _db.Users.Where(a => a.Id == userid).FirstOrDefault();
            c = _db.Courses.Where(a => a.Id == courseid).FirstOrDefault();
            
            if (u.Account > c.Price)
            {
                try
                {
                    //先生成一条BuyOrder记录
                    bo.CourseId = courseid;
                    bo.Course = c;
                    bo.UserId = userid;
                    bo.User = u;
                    _db.BuyOrders.Add(bo);
                    //课程里的购买人数加1
                    c.BuyNum = c.BuyNum + 1;
                    
                    //会员里的总金额减去销售价格
                    u.Account = u.Account - c.Price;
                    
                    //个起保存数据库
                    if (_db.SaveChanges() > 2) 
                    {
                        mes = 0;
                        mark = true;
                    }
                    else
                    {
                        mes = 3;//数据库操作失败！
                    }
                }
                catch (Exception ee)
                {
                    throw ee;
                }

            }
            else
            {
                mes = 2;//余额不足
            }
            
            return mark;
        }

        public bool BuyOrderAdd(out int mes,Guid userid, Guid courseid, Guid couponid)
        {
            bool mark = false;
            //先声明五个对象
            User u = new User();
            u = _db.Users.Where(a => a.Id == userid).FirstOrDefault();
            Course c = new Course();
            c = _db.Courses.Where(a => a.Id == courseid).FirstOrDefault();
            Coupon cp = new Coupon();
            cp = _db.Coupons.Where(a => a.Id == couponid).FirstOrDefault();
            
            BuyOrder bo = new BuyOrder();
            var isbo= _db.BuyOrders.Where(a => a.CourseId == courseid && a.UserId == userid).FirstOrDefault();
            if(isbo!=null)
            {
                mes = 1;//用户已经购买过该课程
                return false;
            }
            
            CouponCourse cc = new CouponCourse();
            CouponsRecord cr = new CouponsRecord();
            cr = _db.CouponsRecords.Where(a => a.CouponId == couponid && a.UserId == userid && a.State==1).FirstOrDefault();
           
            //判断会员的余额加上券的金额够不够买
            if ((u.Account + cp.Price - c.Price) >= 0)
            {
                try
                {
                    //如果够买
                    //生成一条BuyOrder记录
                    bo.CourseId = courseid;
                    bo.Course = c;
                    bo.UserId = userid;
                    bo.User = u;
                    _db.BuyOrders.Add(bo);
                    //生成一条券与课couponCourse的关系记录
                    cc.Course = c;
                    cc.CourseId = courseid;
                    cc.CouponsRecordId = cr.Id;
                    cc.CouponsRecord = cr;
                    _db.CouponCourses.Add(cc);

                    //课程里购买人数加1
                    c.BuyNum = c.BuyNum + 1;
                    
                    //会员里的总金额减销售价格加上券的金额
                    u.Account = u.Account - c.Price + cp.Price;
                    
                    //会员券记录里，找到第一张符合条件的记录，消掉一张券
                    cr.State = 0;
                    
                    //数据库操作
                    if (_db.SaveChanges() >= 5)
                    {
                        mes = 0;
                        mark = true;
                    }
                    else
                    {
                        mes = 3;//数据库操作失败！
                    }
                }
                catch (Exception ee)
                {

                    throw ee;
                }
            }
            else
            {
                mes = 2;//余额不足
                mark = false;
            }

            return mark;
        }
        /// <summary>
        /// 获得一个订单的详累内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public BuyOrderQueryModel getBuyOrder(Guid id)
        {
            BuyOrderQueryModel boqm = new BuyOrderQueryModel();
            boqm = _db.BuyOrders.Where(a => a.Id == id).Select(b => (new BuyOrderQueryModel() { Id = b.Id, Title = b.Course.Title, TeacherName = b.Course.Teacher.Name, CreateDate = b.Course.CreateDate, Detailed = b.Course.Detailed, UserName = b.User.UserName })).FirstOrDefault();
            return boqm;
        }
        /// <summary>
        /// 分页获得一个订单的集合，自定义的模板
        /// </summary>
        /// <param name="total"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>

        public List<BuyOrderQueryModel> getBuyOrderQueryList(out int total, int page = 1, int pageSize = 10)
        {
            var list = _db.BuyOrders.Select(a => (new BuyOrderQueryModel() { Id = a.Course.Id, Title = a.Course.Title, TeacherName = a.Course.Teacher.Name, CreateDate = a.Course.CreateDate, Detailed = a.Course.Detailed, UserName = a.User.UserName }));
            var list2 = list.Skip(pageSize * (page - 1)).Take(pageSize).ToList();
            total = list2.Count();
            return list2;

        }
        /// <summary>
        /// 按照用户查询订单清单
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="total"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<BuyOrderQueryModel> getBuyOrderQueryList(Guid UserId, out int total, int page = 1, int pageSize = 10)
        {
            var list = _db.BuyOrders.Where(b => b.User.Id == UserId).Select(a => (new BuyOrderQueryModel() { Id = a.Course.Id, Title = a.Course.Title, TeacherName = a.Course.Teacher.Name, CreateDate = a.Course.CreateDate, Detailed = a.Course.Detailed, UserName = a.User.UserName }));
            var list2 = list.Skip(pageSize * (page - 1)).Take(pageSize).ToList();
            total = list2.Count();
            return list2;
        }
        /// <summary>
        /// 在指定的时间段时，按标题和类型统计销售量
        /// </summary>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <returns></returns>
        public List<GroupByTimeBuyOrder> GetGroupByTimeBuyOrders(DateTime firstdate, DateTime lastdate)
        {
            if (lastdate > firstdate)
            {
                var list = _db.BuyOrders.Where(a => a.CreatedDate >= firstdate && a.CreatedDate <= lastdate); //.ToList() 最晚去ToList
                var listgroup = list.GroupBy(a => new { a.Course.Title, a.Course.Type }).Select(b => (new GroupByTimeBuyOrder() { Title = b.Key.Title, Type = b.Key.Type, Account = b.Count(), BuyNumberAccout = b.Sum(item => item.Course.BuyNum) })).ToList();
                return listgroup;
            }
            else
            {
                // List < GroupByTimeBuyOrder > List = null;  
                return null;
            }
        }
    }
}
